package com.bittech.everything.core.dao;

import com.alibaba.druid.pool.DruidDataSource;
import com.bittech.everything.config.EverythingConfig;

import javax.sql.DataSource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Author: secondriver
 * Created: 2018/9/27
 */
public final class DataSourceFactory {
    
    private static volatile DruidDataSource dataSource;
    
    private DataSourceFactory() {
    }
    
    /**
     * 通过配置构建数据源
     *
     * @param everythingConfig
     * @return
     */
    public static DataSource dataSource(EverythingConfig everythingConfig) {
        if (dataSource == null) {
            synchronized(DataSourceFactory.class) {
                if (dataSource == null) {
                    dataSource = new DruidDataSource();
                    //H2：采用H2嵌入式数据库
                    dataSource.setUrl("jdbc:h2:" + everythingConfig.getH2IndexFile());
                    dataSource.setDriverClassName("org.h2.Driver");
                    dataSource.setTestWhileIdle(false);
                    //MySQL: 1.注释掉上面关于H2的数据源配置 2.添加MySQL的JDBC驱动 3.修改连接信息
//                    dataSource.setUrl("jdbc:mysql://localhost:3306/everything?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC" +
//                            "&createDatabaseIfNotExist=true");
//                    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
//                    dataSource.setUsername("root");
//                    dataSource.setPassword("root");
                }
            }
        }
        return dataSource;
    }
    
    
    /**
     * 初始化数据库
     */
    public static void databaseInit() {
        DataSource dataSource = DataSourceFactory.dataSource(EverythingConfig.getInstance());
        try (Connection connection = dataSource.getConnection();
             Statement statement = connection.createStatement();
        ) {
            try (InputStream is = DataSourceFactory.class.getClassLoader().getResourceAsStream("database.sql");
            ) {
                if (is == null) {
                    return;
                }
                try (
                        InputStreamReader stream = new InputStreamReader(is);
                        BufferedReader reader = new BufferedReader(stream);
                
                ) {
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }
                    //SQL语句使用逗号(;)分割，此处可以采取拆分之后单条执行
                    statement.execute(sb.toString());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
